package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.Student;

import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.StudentService;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.sql.SQLException;
@WebServlet({"/studentModification/*", "/studentModification"})
public class StudentModificationCtrl extends HttpServlet {
    private StudentService studentService = null;

    @Override
    public void init() throws ServletException {
        studentService = ServiceFactory.getService(StudentService.class, "StudentServiceImpl");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String student_json = JSONUtil.getJSON(request);
        Student studentToAdd = JSON.parseObject(student_json, Student.class);


        JSONObject msg = new JSONObject();

        try {
            studentService.addStudent(studentToAdd);
            msg.put("msg", "增加成功");
            msg.put("code", "200");
        } catch (SQLException e) {
            msg.put("msg", "数据库操作异常");
            msg.put("code", "500");
            e.printStackTrace();
        } catch (Exception e) {
            msg.put("msg", "网络异常");
            msg.put("code", "500");
            e.printStackTrace();
        }
        response.getWriter().println(JSON.toJSONString(msg));
    }


}

